import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/features/community/viewmodels/photography_detail_viewmodel.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/models/comment_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/auth_gate_modal.dart';
import 'package:vista/shared/widgets/complain_bottom_sheet.dart';
import 'package:vista/shared/widgets/vacant_state.dart';

/// 摄影动态详情页面
class PhotographyDetailView extends StatelessWidget {
  final String postId;

  const PhotographyDetailView({super.key, required this.postId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<PhotographyDetailViewModel>.reactive(
      viewModelBuilder:
          () => PhotographyDetailViewModel(
            getIt.get(),
            getIt.get(),
            getIt.get(),
            postId,
          )..initialize(),
      builder: (context, model, child) {
        if (model.isBusy || model.post == null) {
          return Scaffold(
            body: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/my-background.png'),
                  fit: BoxFit.fill,
                ),
              ),
              child: const Center(child: CircularProgressIndicator()),
            ),
          );
        }

        return Scaffold(
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my-background.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: SafeArea(
              bottom: false,
              child: [
                // 标题栏
                _buildHeader(context, model),
                // 可滚动内容
                Expanded(
                  child: SingleChildScrollView(
                    child: [
                          // 图片展示区域
                          _buildImageSection(context, model),
                          SizedBox(height: 14.h),
                          // 发布者信息和摄影参数
                          _buildAuthorAndParamsSection(context, model),
                          SizedBox(height: 14.h),
                          // 评论列表
                          _buildCommentsSection(context, model),
                          SizedBox(height: 100.h), // 底部留白
                        ]
                        .verticalShot(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                        )
                        .frameHorizontal(14.w),
                  ),
                ),
                // 评论输入框
                _buildCommentInput(context, model),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
            ),
          ),
        );
      },
    );
  }

  /// 构建标题栏
  Widget _buildHeader(BuildContext context, PhotographyDetailViewModel model) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => getIt.get<NavigationService>().back(),
            child: Image.asset(
              'assets/images/back.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
          // 举报按钮
          GestureDetector(
            onTap: () async {
              await ComplainHelper.unveil(
                context,
                onComplain: (reason) async {
                  await model.deletePost();
                  if (context.mounted) {
                    getIt.get<NavigationService>().back();
                    FlashNotifier.flashSuccess('Report submitted successfully');
                  }
                },
              );
            },
            child: Image.asset(
              'assets/images/report.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建图片展示区域
  Widget _buildImageSection(
    BuildContext context,
    PhotographyDetailViewModel model,
  ) {
    final post = model.post!;
    final firstImage = post.images.isNotEmpty ? post.images.first : '';

    return GestureDetector(
      onTap: () async {
        await Navigator.of(
          context,
        ).pushNamed(Routes.imageDetail, arguments: {'postId': post.id});
      },
      child: AspectRatio(
        aspectRatio: 346 / 346,
        child: Stack(
          children: [
            // 主图片
            ClipRRect(
              borderRadius: BorderRadius.circular(6.r),
              child:
                  firstImage.isNotEmpty
                      ? Image.asset(
                        firstImage,
                        width: double.infinity,
                        height: double.infinity,
                        fit: BoxFit.cover,
                      )
                      : Container(color: Colors.grey[300]),
            ),
            // community-box.png 叠层
            Positioned.fill(
              child: Image.asset(
                'assets/images/community-box.png',
                fit: BoxFit.fill,
              ),
            ),
            // Container 叠层（标题、详情、小图、查看详情按钮）
            Positioned(
              left: 50.w,
              right: 50.w,
              bottom: 30.h,
              child: GestureDetector(
                onTap: () async {
                  await Navigator.of(context).pushNamed(
                    Routes.imageDetail,
                    arguments: {'postId': post.id},
                  );
                },
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4.r),
                  child: BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 8.w,
                        vertical: 6.h,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.black.withValues(alpha: 0.05),
                        borderRadius: BorderRadius.circular(4.r),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          // 小图
                          if (firstImage.isNotEmpty)
                            Container(
                              width: 36.w,
                              height: 26.w,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4.r),
                                image: DecorationImage(
                                  image: AssetImage(firstImage),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                          if (firstImage.isNotEmpty) SizedBox(width: 8.w),
                          // 标题和详情
                          Expanded(
                            child: [
                              // 标题
                              Text(
                                post.content,
                                style: TextStyle(
                                  fontSize: 8.sp,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.white,
                                ),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ].verticalShot(
                              crossAxisAlignment: CrossAxisAlignment.start,
                            ),
                          ),
                          SizedBox(width: 8.w),
                          // 查看详情按钮
                          Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 6.w,
                              vertical: 6.h,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(44.r),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.visibility,
                                  size: 10.w,
                                  color: Colors.black,
                                ),
                                SizedBox(width: 4.w),
                                Text(
                                  'View Details',
                                  style: TextStyle(
                                    fontSize: 6.sp,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建发布者信息和摄影参数区域
  Widget _buildAuthorAndParamsSection(
    BuildContext context,
    PhotographyDetailViewModel model,
  ) {
    final author = model.author;
    final post = model.post!;
    final photoParams = post.photoParams;

    return Container(
      padding: EdgeInsets.all(14.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6.r),
        boxShadow: [
          BoxShadow(
            color: ColorConstants.blackColor,
            blurRadius: 0,
            offset: Offset(2, 2),
            spreadRadius: 0,
          ),
        ],
      ),
      child: [
        // 发布者信息
        Row(
          children: [
            GestureDetector(
              onTap: () async {
                if (author == null) return;
                // 检查是否是当前用户
                final currentUser = await getIt<AuthFocus>().getCurrentUser();
                if (currentUser != null && currentUser.id == author.id) {
                  return; // 是自己的头像，不跳转
                }
                // 跳转到他人主页
                if (context.mounted) {
                  await Navigator.of(context).pushNamed(
                    Routes.otherProfile,
                    arguments: {'userId': author.id},
                  );
                }
              },
              child: CircleAvatar(
                radius: 22.r,
                backgroundColor: ColorConstants.primaryColor,
                backgroundImage:
                    author?.avatar != null ? AssetImage(author!.avatar!) : null,
                child:
                    author?.avatar == null
                        ? Icon(Icons.person, size: 22.w, color: Colors.white)
                        : null,
              ),
            ),
            SizedBox(width: 10.w),
            Expanded(
              child: [
                Text(
                  author?.username ?? 'Unknown',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w700,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w700,
                        ).fontFamily,
                    color: Colors.black87,
                  ),
                ),
                if (author?.signature != null) ...[
                  SizedBox(height: 4.h),
                  Text(
                    author!.signature!,
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontFamily:
                          GoogleFonts.alegreyaSans(
                            fontWeight: FontWeight.w400,
                          ).fontFamily,
                      color: Colors.black54,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
            ),
            // 前往主页按钮
            GestureDetector(
              onTap: () async {
                // 检查是否是当前用户
                final currentUser = await getIt<AuthFocus>().getCurrentUser();
                if (currentUser != null && currentUser.id == author?.id) {
                  FlashNotifier.flashInfo('You are the author');
                  return; // 是自己的头像，不跳转
                }
                // 跳转到他人主页
                if (context.mounted) {
                  await Navigator.of(context).pushNamed(
                    Routes.otherProfile,
                    arguments: {'userId': author?.id},
                  );
                }
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
                decoration: BoxDecoration(
                  color: ColorConstants.blueColor,
                  borderRadius: BorderRadius.circular(6.r),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [Icon(Icons.home, size: 16.w, color: Colors.white)],
                ),
              ),
            ),
            SizedBox(width: 8.w),
            // 关注按钮
            if (model.currentUser != null &&
                model.currentUser!.id != author?.id)
              InkWell(
                onTap: () async {
                  if (model.currentUser == null) {
                    final result = await showDialog<bool>(
                      context: context,
                      builder: (context) => const AuthGateModal(),
                    );
                    if (result == true && context.mounted) {
                      await Navigator.of(context).pushNamed('/login');
                      if (context.mounted) {
                        await model.refreshAuthAndLikeStatus();
                      }
                    }
                    return;
                  }
                  await model.toggleFollow();
                },
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 8.h,
                  ),
                  decoration: BoxDecoration(
                    color:
                        model.isFollowing
                            ? ColorConstants.accentColor
                            : ColorConstants.primaryColor,
                    borderRadius: BorderRadius.circular(6.r),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        model.isFollowing ? Icons.check : Icons.add,
                        size: 16.w,
                        color: Colors.white,
                      ),
                      SizedBox(width: 4.w),
                      Text(
                        model.isFollowing ? 'Following' : 'Follow',
                        style: TextStyle(fontSize: 14.sp, color: Colors.white),
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
        if (photoParams != null) ...[
          SizedBox(height: 16.h),
          Divider(color: Colors.grey[300], height: 1),
          SizedBox(height: 16.h),
          // 摄影参数
          Text(
            'Photo Parameters',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w700,
              fontFamily:
                  GoogleFonts.alegreyaSans(
                    fontWeight: FontWeight.w700,
                  ).fontFamily,
              color: Colors.black87,
            ),
          ),
          SizedBox(height: 12.h),
          _buildPhotoParams(photoParams),
        ],
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
    );
  }

  /// 构建摄影参数
  Widget _buildPhotoParams(photoParams) {
    return [
      _buildParamItem('Camera', photoParams.camera),
      SizedBox(height: 8.h),
      _buildParamItem('Lens', photoParams.lens),
      SizedBox(height: 8.h),
      _buildParamItem('Focal Length', photoParams.fl),
      SizedBox(height: 8.h),
      _buildParamItem('Aperture', photoParams.aperture),
      SizedBox(height: 8.h),
      _buildParamItem('Shutter Speed', photoParams.shutter),
      SizedBox(height: 8.h),
      _buildParamItem('ISO', photoParams.iso),
      SizedBox(height: 8.h),
      _buildParamItem('Exposure', photoParams.exposure),
      SizedBox(height: 8.h),
      _buildParamItem('Flash', photoParams.flash),
    ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start);
  }

  /// 构建单个参数项
  Widget _buildParamItem(String label, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 14.sp,
            fontFamily:
                GoogleFonts.alegreyaSans(
                  fontWeight: FontWeight.w400,
                ).fontFamily,
            color: Colors.black54,
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w600,
            fontFamily:
                GoogleFonts.alegreyaSans(
                  fontWeight: FontWeight.w600,
                ).fontFamily,
            color: Colors.black87,
          ),
        ),
      ],
    );
  }

  /// 构建评论列表区域
  Widget _buildCommentsSection(
    BuildContext context,
    PhotographyDetailViewModel model,
  ) {
    if (model.comments.isEmpty) {
      return Container(
        padding: EdgeInsets.all(14.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6.r),
          boxShadow: [
            BoxShadow(
              color: ColorConstants.blackColor,
              blurRadius: 0,
              offset: Offset(2, 2),
              spreadRadius: 0,
            ),
          ],
        ),
        child: VacantState(
          message: 'No comments yet',
          imagePath: 'assets/images/empty2.png',
        ),
      );
    }

    return Container(
      padding: EdgeInsets.all(14.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6.r),
        border: Border.all(color: Colors.black),
        boxShadow: [
          BoxShadow(
            color: ColorConstants.blackColor,
            blurRadius: 0,
            offset: Offset(2, 2),
            spreadRadius: 0,
          ),
        ],
      ),
      child: [
        Text(
          'Comments',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w800,
            color: Colors.black87,
          ),
        ),
        SizedBox(height: 12.h),
        ...model.comments.map(
          (comment) => _buildCommentItem(context, model, comment),
        ),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  /// 构建单个评论项
  Widget _buildCommentItem(
    BuildContext context,
    PhotographyDetailViewModel model,
    CommentShot comment,
  ) {
    return FutureBuilder<UserFrame?>(
      future: model.getCommentUser(comment.userId),
      builder: (context, snapshot) {
        final user = snapshot.data;

        return Container(
          margin: EdgeInsets.only(bottom: 12.h),
          decoration: BoxDecoration(
            color: ColorConstants.primaryColor,
            borderRadius: BorderRadius.circular(10.r),
          ),
          child: Stack(
            children: [
              // 主要内容
              Padding(
                padding: EdgeInsets.all(12.w),
                child: [
                  // 用户信息行
                  Row(
                    children: [
                      // 用户头像
                      GestureDetector(
                        onTap: () async {
                          if (user == null) return;
                          // 检查是否是当前用户
                          final currentUser =
                              await getIt<AuthFocus>().getCurrentUser();
                          if (currentUser != null &&
                              currentUser.id == user.id) {
                            return; // 是自己的头像，不跳转
                          }
                          // 跳转到他人主页
                          if (context.mounted) {
                            await Navigator.of(context).pushNamed(
                              Routes.otherProfile,
                              arguments: {'userId': user.id},
                            );
                          }
                        },
                        child: CircleAvatar(
                          radius: 15.r,
                          backgroundColor: ColorConstants.primaryColor,
                          backgroundImage:
                              user?.avatar != null
                                  ? AssetImage(user!.avatar!)
                                  : null,
                          child:
                              user?.avatar == null
                                  ? Icon(
                                    Icons.person,
                                    size: 20.w,
                                    color: Colors.white,
                                  )
                                  : null,
                        ),
                      ),
                      SizedBox(width: 10.w),
                      // 用户名
                      Expanded(
                        child: Text(
                          user?.username ?? 'Unknown',
                          style: TextStyle(
                            fontSize: 15.sp,
                            fontWeight: FontWeight.w600,
                            fontFamily:
                                GoogleFonts.alegreyaSans(
                                  fontWeight: FontWeight.w600,
                                ).fontFamily,
                            color: Colors.black87,
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 10.h),
                  // 评论内容
                  Text(
                    comment.content,
                    style: TextStyle(
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w400,
                      color: Colors.black87,
                      height: 1.5,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  // 时间（右下角）
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text(
                        _formatTime(comment.timestamp),
                        style: TextStyle(
                          fontSize: 12.sp,
                          fontFamily:
                              GoogleFonts.alegreyaSans(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                          color: Colors.black54,
                        ),
                      ),
                    ],
                  ),
                ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
              ),
              // 右上角举报按钮
              Positioned(
                top: 8.h,
                right: 8.w,
                child: GestureDetector(
                  onTap: () async {
                    await ComplainHelper.unveil(
                      context,
                      onComplain: (reason) async {
                        await model.deleteComment(comment.id);
                        if (context.mounted) {
                          FlashNotifier.flashSuccess(
                            'Report submitted successfully',
                          );
                        }
                      },
                    );
                  },
                  child: Container(
                    padding: EdgeInsets.all(6.w),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.8),
                      borderRadius: BorderRadius.circular(12.r),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 4,
                          spreadRadius: 1,
                        ),
                      ],
                    ),
                    child: Image.asset(
                      'assets/images/report.png',
                      width: 16.w,
                      height: 16.w,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建评论输入框
  Widget _buildCommentInput(
    BuildContext context,
    PhotographyDetailViewModel model,
  ) {
    final textController = TextEditingController();

    return Container(
      padding: EdgeInsets.all(14.w),
      decoration: BoxDecoration(color: Colors.transparent),
      child: SafeArea(
        top: false,
        child: Row(
          children: [
            Expanded(
              child: TextField(
                controller: textController,
                decoration: InputDecoration(
                  hintText: 'Add a comment...',
                  hintStyle: TextStyle(fontSize: 14.sp, color: Colors.white),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(
                      color: ColorConstants.accentColor,
                      width: 1.w,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(
                      color: ColorConstants.accentColor,
                      width: 1.w,
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(
                      color: ColorConstants.accentColor,
                      width: 1.w,
                    ),
                  ),
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 10.h,
                  ),
                ),
                onSubmitted: (value) async {
                  if (model.currentUser == null) {
                    final result = await showDialog<bool>(
                      context: context,
                      builder: (context) => const AuthGateModal(),
                    );
                    if (result == true && context.mounted) {
                      await Navigator.of(context).pushNamed('/login');
                      if (context.mounted) {
                        await model.refreshAuthAndLikeStatus();
                      }
                    }
                    return;
                  }

                  if (value.trim().isNotEmpty) {
                    await model.addComment(value);
                    FlashNotifier.flashSuccess('Comment sent successfully');
                    textController.clear();
                  }
                },
              ),
            ),
            SizedBox(width: 10.w),
            GestureDetector(
              onTap: () async {
                final value = textController.text;
                if (model.currentUser == null) {
                  final result = await showDialog<bool>(
                    context: context,
                    builder: (context) => const AuthGateModal(),
                  );
                  if (result == true && context.mounted) {
                    await Navigator.of(context).pushNamed('/login');
                    if (context.mounted) {
                      await model.refreshAuthAndLikeStatus();
                    }
                  }
                  return;
                }

                if (value.trim().isNotEmpty) {
                  await model.addComment(value);
                  FlashNotifier.flashSuccess('Comment sent successfully');
                  textController.clear();
                }
              },
              child: Container(
                width: 44.w,
                height: 44.w,
                decoration: BoxDecoration(
                  color: ColorConstants.accentColor,
                  borderRadius: BorderRadius.circular(8.r),
                ),
                padding: EdgeInsets.all(10.w),
                child: Image.asset(
                  'assets/images/send.png',
                  width: 20.w,
                  height: 20.w,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 格式化时间
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}m ago';
    } else {
      return 'Just now';
    }
  }
}
